package org.blade.personal.framework.orm.loader.concre;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;

import org.blade.personal.framework.orm.loader.Loader;
import org.blade.personal.framework.session.ResultHandler;

/**
 * 实体装载器
 * @author ZGF
 *
 */
public class EntityLoader implements Loader {

	
	private ResultHandler resultHandler;
	
	/**
	 * 实体架载器
	 * @param rh
	 */
	public EntityLoader(ResultHandler rh) {
		this.resultHandler = rh;
	}
	
	@Override
	public Object get(String clazzName) {
		
		return resultHandler.getEntityName(clazzName);
	}

	@Override
	public void setAttributeValue(Object obj, Field field, Object value) {
		
		if(field.isAccessible()){
			try {
				field.set(obj, value);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	@Override
	public List load(ResultSet rs) {
		return this.load(rs, resultHandler);
	}
	
	
	@Override
	public List	 load(ResultSet rs, ResultHandler resultHandler) {

//		Object resultItem = resultHandler.get("");

		try {
			ResultSetMetaData rsmd = rs.getMetaData();
			
			int columnCount = rsmd.getColumnCount();
			
			String []columnsNames = new String[rsmd.getColumnCount()];
			
			for(int i = 0; i < columnCount ; i++){
				
				String columnName = rsmd.getColumnName(i+1);
				columnsNames[i] = columnName;
				String className = this.resultHandler.getEntityName(columnName);
				
				Class entityInstance = Class.forName(className); 
				System.out.println(entityInstance.getName());
				
			}
			
			while(rs.next()){
				
				for(String colsName : columnsNames){
					System.out.println(colsName);
					System.out.println(rs.getObject(colsName));
				}
				
			}
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		return null;
	}
	

}
